package com.tsing.cedap.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@ServerEndpoint(value = "/websocket/aliPayNotify/{id}")
@Component
public class WebSocketManager {

    private static int onlineCount = 0;

    private static CopyOnWriteArraySet<WebSocketManager> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    private String id = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.warn("客户端：" + id + " 连接成功，当前在线人数为：" + getOnlineCount());
        this.id = id;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.warn("有一个连接关闭，当前在线人数为：" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.warn("收到来自客户端：" + id + " 的信息：" + message);
        for (WebSocketManager item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message, @PathParam("id") String id) {
        log.warn("推送消息到客户端：" + id + "，内容： " + message);
        for (WebSocketManager item : webSocketSet) {
            try {
                // 这里可以设定只推送给这个id的，为null则全部推送
                if (id == null) {
                    item.sendMessage(message);
                } else if (item.id.equals(id)) {
                    item.sendMessage(message);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketManager.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketManager.onlineCount--;
    }

}
